"""
Author : ZhengShiQi
DateTime: 2025/9/11 14:00
FileName: db_service.py
description: 封装数据库的CRUD操作
"""
from sqlalchemy.orm import Session
from app.models.database import MockApiConfig
from app.models.schemas import MockApiCreate
from app.models.schemas import HttpMethod

# 创建模拟API配置
def create_mock_api(db: Session, mock_api: MockApiCreate, wiremock_id: str = None):
    db_mock = MockApiConfig(
        id=mock_api.id if hasattr(mock_api, 'id') else None,  # 使用传入的ID
        wiremock_id=wiremock_id,  # 使用传入的WireMock ID
        name=mock_api.name,
        url=mock_api.url,  # 存储url
        method=mock_api.method if hasattr(mock_api, 'method') else HttpMethod.GET,  # 存储method，默认为GET
        headers=mock_api.headers,  # 存储headers
        body=mock_api.body if mock_api.body else None,  # 存储body
        status_code=mock_api.status_code,  # 存储status_code

        status=mock_api.status if hasattr(mock_api, 'status') else True  # 存储status，默认为True
    )
    db.add(db_mock)
    db.commit()
    db.refresh(db_mock)
    return db_mock

# 查询所有模拟API配置
def get_all_mock_apis(db: Session, skip: int = 0, limit: int = 100):
    return db.query(MockApiConfig).offset(skip).limit(limit).all()

# 根据ID获取模拟API配置
def get_mock_api_by_id(db: Session, id: int):
    return db.query(MockApiConfig).filter(MockApiConfig.id == id).first()

# 更新模拟API配置
def update_mock_api(db: Session, id: int, mock: MockApiCreate):
    db_mock = db.query(MockApiConfig).filter(MockApiConfig.id == id).first()
    if db_mock:
        update_data = mock.dict()
        # 保留wiremock_id字段
        update_data.pop('wiremock_id', None)
        for key, value in update_data.items():
            # 如果wiremock_id为空，则不更新该字段
            if key == 'wiremock_id' and not value:
                continue
            setattr(db_mock, key, value)
        db.commit()
        db.refresh(db_mock)
    return db_mock

# 删除模拟API配置
def delete_mock_api(db: Session, id: int):
    db_mock = db.query(MockApiConfig).filter(MockApiConfig.id == id).first()
    if db_mock:
        db.delete(db_mock)
        db.commit()
    return db_mock